package com.daichi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daichi.common.lang.Result;
import com.daichi.controller.base.BaseController;
import com.daichi.entity.Blog;
import com.daichi.service.BlogService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Daichi Chou
 * @since 2021-05-27
 */
@RestController
public class BlogController extends BaseController {

    private final BlogService blogService;

    @Autowired
    public BlogController(BlogService blogService) {
        this.blogService = blogService;
    }

    @GetMapping("/blogs")
    public Result blogs(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page<Blog> page = new Page<>(currentPage, 5);
        IPage<Blog> blogs = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.succ(blogs);

    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable("id") Long id) {

        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客不存在");

        return Result.succ(blog);
    }

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {

        Blog temp = null;

        // 如果传来的blog的id为空则为新增，否则为修改
        if (blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            Assert.isTrue(temp.getUserId().longValue() == getProfileId().longValue(), "没有权限编辑");
        } else {
            temp = new Blog();
            temp.setUserId(getProfileId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtils.copyProperties(blog, temp, "id", "userId", "created", "status");

        blogService.saveOrUpdate(temp);

        return Result.succ(null);
    }

    @RequiresAuthentication
    @DeleteMapping("/blog/{id}")
    public Result delete(@PathVariable("id") Long id) {

        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客不存在");
        Assert.isTrue(blog.getUserId().longValue() == getProfileId(), "没有权限删除");

        boolean success = blogService.removeById(id);
        Assert.isTrue(success, "删除失败");

        return Result.succ(null);
    }

}
